package com.maben.mqtt.controller;

import com.maben.mqtt.constant.YmlConstant;
import com.maben.mqtt.mapper.IMqttSender;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * 发送测试控制类
 */
@RestController
public class SendController {

    /**
     * 注入发送MQTT的Bean
     */
    @Resource
    private IMqttSender iMqttSender;
    @Resource
    private YmlConstant ymlConstant;

    /**
     * 测试发送消息
     */
    @RequestMapping("/sendMessage")
    public String sendMessage(Integer qos, String topic, String message) {
        try {
            if (Objects.isNull(qos)) {
                qos = 2;
            }
            if (StringUtils.isBlank(topic)) {
                topic = ymlConstant.getProviderDefaultTopic();
            }
            message+=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSS").format(new Date());
            iMqttSender.sendToMqtt(topic, qos, message);
            return "发送成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "发送失败";
        }
    }

}
